package com.trip.wechat.platform.service.impl;

import com.google.common.base.Strings;
import com.trip.wechat.platform.datastore.MpAccountStore;
import com.trip.wechat.platform.model.AccountBO;
import com.trip.wechat.platform.model.AuthResultBO;
import com.trip.wechat.platform.model.user.UserBO;
import com.trip.wechat.platform.model.user.UserInfoBO;
import com.trip.wechat.platform.service.OAuthService;
import com.trip.wechat.platform.service.UserService;
import com.trip.wechat.platform.subsystem.OAuth2Facade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 功能说明: <br>
 * 系统说明: <br>
 * 模块说明: <br>
 * 功能描述: <br>
 * <br>
 */
@Service
public class OAuthServiceImpl implements OAuthService {

    final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MpAccountStore accountStore;
    @Autowired
    OAuth2Facade auth2Facade;
    @Autowired
    UserService userService;

    @Override
    public UserInfoBO fetchUserByAuth(String publicKey, String code) {

        Optional<AccountBO> op = accountStore.get(publicKey);
        if (!op.isPresent()) {
            LOGGER.info("[OAuthService.fetchUserByAuth] failed! unknown publicKey:{}", publicKey);
//            return createErrorResult(CodeDict.C_SERVICE_FAIL, "unknown publicKey");
        }

        AuthResultBO authResultBO = auth2Facade.auth(op.get().getAppId(), op.get().getAppSecret(), code);
        UserInfoBO userInfoBO = new UserInfoBO();
        userInfoBO.setErrcode(authResultBO.getErrcode());
        userInfoBO.setErrmsg(authResultBO.getErrmsg());
        userInfoBO.setOpenid(authResultBO.getOpenid());

        if (!Strings.isNullOrEmpty(userInfoBO.getOpenid())) {
            try {
                UserBO userBO = userService.queryUserInfoByOpenidFromDB(publicKey, userInfoBO.getOpenid());
                if(userBO !=null){
                    BeanUtils.copyProperties(userBO, userInfoBO);
                }
            } catch (Exception e){//查询失败不抛错
                LOGGER.error("[OAuthService.fetchUserByAuth] query UserInfo ByOpenid[{}], publicKey[{}] FromDB failed"
                        , userInfoBO.getOpenid(), publicKey, e);
            }
        }

        return userInfoBO;
    }

    protected UserInfoBO createErrorResult(int code, String message) {
        UserInfoBO result = new UserInfoBO();
        result.setErrcode(code);
        result.setErrmsg(message);
        return result;
    }
}
